package db;

import java.sql.Connection;
//import java.sql.DriverManager;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * Provides <code>java.sql.Connection</code> objects.
 * 
 */
public class DbConnectionPool {

    // Registering Postgresql JDBC driver with the DriverManager
	//static {
    //    try {
	//		Class.forName("org.postgresql.Driver");
	//	} catch (ClassNotFoundException e) {
	//		throw new RuntimeException(e);
	//	}
	//}

	/**
	 * Returns a <code>java.sql.Connection</code> object.
	 * 
	 * @exception NamingException
	 *                if the JDBC resource is not found
	 * @exception SQLException
	 *                if a connection can not be obtained
	 * 
	 * @return Connection to use
	 */
	public static Connection getConnection() throws NamingException,
			SQLException {
		
		// Obtain the environment naming context
		Context initCtx = new InitialContext();
		// Look up the data source
		DataSource ds = (DataSource)
				initCtx.lookup("java:/comp/env/jdbc/ClassesDbPool");


		
		// Allocate and use a connection from the pool
		return ds.getConnection();

		// TODO: To be replaced with real connection pool after we have covered it in class
        //return DriverManager.getConnection(
        //        "jdbc:postgresql://localhost/students-database?" +
        //        "user=postgres&password=postgres");
	}

}
